package org.logistics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.logistics.R;
import org.logistics.R.id;
import org.logistics.R.layout;
import org.logistics.R.menu;
import org.logistics.bean.MapInforBean;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.TextItem;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.mapapi.utils.CoordinateConvert;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
/**
 * 实时监控
 * @author yimou
 *
 */
public class RealTimeMapActivity extends Activity {

	private BMapManager cMapManager = null ;
	/**
	 * 用户账号
	 * 
	 */
	private String userAccount;
	
	/**
	 * 车辆定位编号
	 * 
	 */
	private int centerNum;
	
	/**
	 * 坐标接口对象集合
	 */
	List<MapInforBean> mapInforList = new ArrayList<MapInforBean>();
	/**
	 * 包名
	 */
	final static String TAG = "org.RealTimeMapActivity.logistics";
	/**
	 *  MapView 是地图主控件
	 */
	private MapView m2MapView = null;
	/**
	 *  用MapController完成地图控制 
	 */
	private MapController mMapController = null;
	/**
	 *  MKMapViewListener 用于处理地图事件回调
	 */
	MKMapViewListener mMapListener = null;
	
	/**
	 * 定时刷新的线程
	 */
	private Handler handler_realtime = new Handler();
	private Runnable runnable = new Runnable() {
        public void run() {
        	handler_realtime.removeCallbacks(runnable);
            this.update();
        }
        void update() {
        	Toast.makeText(getApplicationContext(), "刷新数据",
          		     Toast.LENGTH_SHORT).show();
        	
        	//刷新次数加一
        	refreshTimes++;
        	Log.i(TAG, "刷新"+refreshTimes+"次");
        	
        	//重置全局数据
        	 mapInforList = new ArrayList<MapInforBean>();
        	 p = null;
        	 
        	 //请求服务器
        	 try {
 				mapInforList = getLocalPlace();
 			} catch (IllegalStateException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} catch (JSONException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			} catch (IOException e) {
 				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
        	 
        	 //30秒刷新一次
        	 refresh();
        }
    }; 
    
    /**
     * 刷新次数
     */
    private int refreshTimes = 0;
    /**
     * 定位中心点
     */
    GeoPoint p  = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		setContentView(R.layout.activity_real_time_map);
		
		//获得用户信息  定位车辆信息
				Intent intent = new Intent();
				intent = getIntent();
				userAccount = intent.getStringExtra("userAccount");
				centerNum = intent.getIntExtra("centerNum" , 0);
				
				//请求服务器
				 try {
						mapInforList = getLocalPlace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
			        
				 m2MapView = (MapView)findViewById(R.id.realTimeMapView);
				 m2MapView.setBuiltInZoomControls(true);
				   
				 m2MapView.setVisibility(View.VISIBLE);
				 //重启地图
				 m2MapView.onResume();
					/**
			        * 获取地图控制器
			        */
			       mMapController = m2MapView.getController();
			       /**
			        *  设置地图是否响应点击事件  .
			        */
			       mMapController.enableClick(true);
			       /**
			        * 设置地图缩放级别
			        */
			       mMapController.setZoom(16);
			       
			       
			       //30秒刷新一次
			       refresh();
	}
	
	/**
	 * 回调处理函数
	 */
	@Override  
	protected void onDestroy(){  
		m2MapView.getOverlays().clear();
			//mMapView.setVisibility(View.INVISIBLE);
	        handler_realtime.removeCallbacks(runnable); //停止刷新
	        m2MapView.destroy();
	        finish();
	        super.onDestroy();  
	}  
	
	
	/**
	 * 循环代码
	 */
	public void refresh(){
		 	
			MyLocationOverlay myLocationOverlay = new MyLocationOverlay(m2MapView); 
			LocationData locData = new LocationData();  
			Log.i(TAG, "centerNum = "+ centerNum);
			locData.latitude = (double)(mapInforList.get(centerNum).getH());  
		    locData.longitude = (double)(mapInforList.get(centerNum).getI());  
		    myLocationOverlay.setData(locData);  
		   
		    m2MapView.getOverlays().add(myLocationOverlay);  
	       GeoPoint ep = new GeoPoint((int)(locData.latitude*1e6),  
	    	       (int)(locData.longitude* 1e6));
	        p = CoordinateConvert.fromWgs84ToBaidu(ep);
	        mMapController.animateTo(p);  
	       
	      //颜色定义
			Symbol textSymbol = new Symbol();  
		   	Symbol.Color textColor = textSymbol.new Color();  
		   	textColor.alpha = 255;  
		   	textColor.red = 0;  
		   	textColor.blue = 255;  
		   	textColor.green = 0;  
		   	Symbol textSymbol1 = new Symbol();    
		   	Symbol.Color textColor1 = textSymbol1.new Color();    
		   	textColor1.alpha = 150;    
		   	textColor1.red = 80;    
		   	textColor1.blue = 80;    
		   	textColor1.green = 80;
		   	//初始化文字
		   	TextItem textItem = new TextItem();  
	   	   	textItem.fontColor = textColor;  
	   	   	textItem.bgColor = textColor1;  
	   	   	textItem.fontSize = 20;  
	   	   	String carNum = mapInforList.get(centerNum).getCarNum().toString();
	   	   	double speed = mapInforList.get(centerNum).getSpeed();
	   	   	textItem.text = carNum +"---"+ speed+"km/h";  
	   	   	textItem.pt = p;
	   	   	
	   	 Drawable mark= getResources().getDrawable(R.drawable.nav_turn_via_1);
	   	   	
	   	   m2MapView.getOverlays().clear();
	       TextOverlay textOverlay = new TextOverlay(m2MapView);
	       textOverlay.addText(textItem);
	       m2MapView.getOverlays().add(textOverlay);
	       
	       m2MapView.refresh(); 
	       handler_realtime.postDelayed(runnable, 1000 * 10);
		
	}
	
	
	
	

	
	
	/**
	 * 
	 *请求服务器得到坐标信息对象
	 * @throws JSONException 
	 * @throws IOException 
	 * @throws IllegalStateException
	 */
	public List<MapInforBean> getLocalPlace() throws JSONException, IllegalStateException, IOException {
		BufferedReader in = null;
		/**
		 * 发送请求
		 */
		try {
			Log.i(TAG, "发出请求");
			String request = "http://sj.jy100.com/GetRealtime2.ashx?userName="+userAccount+"&address=true";
			HttpClient hc = new DefaultHttpClient();
			HttpPost hp = new HttpPost(request);
			HttpResponse response = hc.execute(hp);  
	        in = new BufferedReader(  
	                new InputStreamReader(  
	                        response.getEntity().getContent()));  
	        StringBuffer string = new StringBuffer("");  
	        String lineStr = "";  
	        while ((lineStr = in.readLine()) != null) {  
	            string.append(lineStr + "\n");  
	        }  
	        in.close();  
	        String resultStr = string.toString();  
	        Log.i(TAG, resultStr);
	        
	        /**
	         * 解析字符串
	         */
	        JSONObject jo = new JSONObject(resultStr);
	        
	        /**
	         * 得到数据条数
	         * TotalCount
	         */
	        int totalCount = jo.getInt("TotalCount");
	        Log.i(TAG, "共有"+totalCount+"条数据");
	        
	        /**
	         * 把解析数据转保存在对象
	         */
	        JSONArray jsonList = jo.getJSONArray("RootResults");
	        
	        for(int i = 0 ; i < totalCount ; i++  )
	        {
	        	JSONObject temp = new JSONObject(jsonList.getString(i));
	        	MapInforBean mifb = new MapInforBean();
	        	mifb.setCarNum(temp.getString("A"));
	        	mifb.setiMei(temp.getString("D"));
	        	mifb.setOnLine(temp.getBoolean("F"));
	        	mifb.setLocationTime(temp.getString("G"));
	        	mifb.setH(temp.getDouble("H"));
	        	mifb.setI(temp.getDouble("I"));
	        	mifb.setAngle(temp.getInt("K"));
	        	mifb.setSpeed(temp.getDouble("J"));
	        	mifb.setMileage(temp.getDouble("L"));
	        	mifb.setStatue(temp.getString("M"));
	        	mifb.setAddress(temp.getString("O"));
	        	mapInforList.add(mifb);
	        }
			
		} catch (JSONException e) {
			Log.i(TAG, e.getMessage());
		}finally {  
            if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }
		
		return mapInforList;  
		
		
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.real_time_map, menu);
		return true;
	}

}
